from django.http import HttpResponse
from django.shortcuts import render, redirect
import requests
from joblib.externals.cloudpickle import instance


# Create your views here.

def login(request):
    return render(request, "login.html")

def index(request):
    userinfo = request.session.get('user')
    print(userinfo)
    # 未登录
    if not userinfo:
        return redirect("login")
    # 已登录
    return render(request, "index.html", userinfo)

def wx_auth(request):

    # # https://www.5xclass.cn/wx/auth/?code=081HIsFa1gLCCI0VjkGa1unkYJ1HIsFA&state=undefined
    #print(request.GET)

    # 1.获取access token
    code = request.GET['code']
    app_id = "wxf21cb609cb84dc54"
    app_secret = "39ff9c55eb64754ced559ce59429da63"
    url = f"https://api.weixin.qq.com/sns/oauth2/access_token?appid={app_id}&secret={app_secret}&code={code}&grant_type=authorization_code"
    res = requests.get(url)
    res_dict = res.json()
    #print(res_dict)

    # 如果获取access token失败
    if not res_dict.get('errcode'):
        access_token = res_dict['access_token']
        openid = res_dict['openid']

        # 2.根据access token获取用户信息
        url = f"https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}"
        res = requests.get(url)
        res.encoding = 'utf-8'
        user_dict = res.json()
        print(user_dict)

        # 如果获取用户信息失败
        #if user_dict.get('errcode'):
            # return redirect("login")

    else:
        # return redirect("login")
        user_dict = {"nickname": "ADL", "openid": "SDSDHSJGHF98756DSD", "unionid": "SDSDHSJGHF98756DSD"}


    """
        用户唯一标识
            openid => 针对当前应用
            unionid => 针对当前开发者平台
        姓名
        头像
    """

    # 3.保存数据库（注册，登录）
    from app01 import models;
    instance, _ = models.UserInfo.objects.update_or_create(
        defaults={"name": user_dict['nickname']},
        open_id = user_dict['openid'],
        union_id = user_dict['unionid']
    )

    # 4.将用户信息写入session
    request.session['user'] = {"id": instance.id, 'name': instance.name}

    return redirect("index")

def quit(request):
    request.session.clear()
    # print(request.session.get('user'))
    return redirect("login")
